package com.electric.qrapp.utils.system

import android.os.Bundle
import androidx.annotation.IdRes
import androidx.appcompat.app.AppCompatActivity
import androidx.fragment.app.Fragment
import androidx.navigation.NavArgument
import androidx.navigation.NavOptions
import androidx.navigation.fragment.NavHostFragment
import androidx.navigation.fragment.findNavController
import com.electric.qrapp.ui.base.act.SimpleActivity
import com.electric.qrapp.ui.base.frg.SimpleFragment

/**
 *@author created by WA03675
 *@date  2021/9/25 20:25
 *@des Activity fragment 扩展函数
 */
fun SimpleActivity.toast(msg: String?) {
    showToast(this, msg)
}

fun SimpleActivity.finishAct() {
    finishAfterTransition()
}

fun SimpleActivity.getNavHostFragment(@IdRes fragmentContainerViewId: Int): NavHostFragment {
    return  supportFragmentManager.findFragmentById(fragmentContainerViewId) as NavHostFragment
}


fun SimpleActivity.navigate(
    @IdRes fragmentContainerId: Int,
    @IdRes fragmentId: Int,
    bundle: Bundle? = null,
    options: NavOptions? = null
) {
    val navController =
        getNavHostFragment(fragmentContainerId).findNavController()
    navController.navigate(fragmentId, bundle, options)
}

//使用navigation 获取当前fragment
@Suppress("UNCHECKED_CAST")
fun <F : Fragment> AppCompatActivity.getFragment(fragmentClass: Class<F>): F? {
    val navHostFragment = this.supportFragmentManager.fragments.first() as NavHostFragment

    navHostFragment.childFragmentManager.fragments.forEach {
        if (fragmentClass.isAssignableFrom(it.javaClass)) {
            return it as F
        }
    }

    return null
}

fun  SimpleActivity.navArgument(value:Any): NavArgument {
    return NavArgument.Builder().setDefaultValue(value).build()
}



//=======================Fragment===========================

fun SimpleFragment.finish() {
    activity?.run {
        if (this is SimpleActivity) {
            finishAct()
        }
    }
}

fun SimpleFragment.toast(msg: String?) {
    activity?.run {
        if (this is SimpleActivity) {
            showToast(msg = msg)
        }
    }
}
